<!-- 业务详情 -->
<template>
  <div class="overview-detail">
    <div>
      <a-card :bordered="false">
        <!-- 详情表单展示 start -->
        <a-row :gutter="48">
          <a-col :md="18" :sm="24">
            <a-descriptions v-if="$auth('PROJECT.BASIC_DETAIL')" :title="$t('all.autotext720')"></a-descriptions>
          </a-col>
          <a-col :md="6" :sm="24" align="right">
            <a-button
              type="primary"
              style="margin-right: 8px"
              @click="clickEditMessage"
              v-if="$auth('PROJECT.PROJECT_EDIT')"
            >
              {{ $t('all.autotext919') }}
            </a-button>
            <a-popconfirm
              :oktext="$t('all.autotext379')"
              :canceltext="$t('all.autotext975')"
              :title="dynamicTitle"
              @confirm="deleteProject"
              @visibleChange="handleVisibleChange"
            >
              <a-button
                type="danger"
                v-if="$auth('PROJECT.PROJECT_DELETE') && this.detailsInfo.status != 2 && !projectClosed"
              >
                {{ $t('all.autotext379') }}
              </a-button>
            </a-popconfirm>
          </a-col>
        </a-row>
        <a-descriptions v-if="$auth('PROJECT.BASIC_DETAIL')" bordered title="">
          <!-- ******************************接口暂无数据返回先将其注释，否则影响界面展示****************************************** -->
          <a-descriptions-item :label="$t('all.autotext211')" :span="3"> {{ detailsInfo.name || '' }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext345')"> {{ detailsInfo.status | enumValueByKey($const.PROJECT_STATUS) }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext992')"> {{ detailsInfo.no || '' }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext873')"> {{ detailsInfo.protocolNo }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext1718')">{{ detailsInfo.businessCode }}</a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext1789')">{{ detailsInfo.customerName }}</a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext21')"> {{ detailsInfo.createTime | moment }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext1273')">{{ detailsInfo.sponsorName }}</a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext863')"> {{ detailsInfo.stage | enumValueByKey($const.SPONSOR_STAGE) }} </a-descriptions-item>
          <!-- 最后一条 业务人员看到的是业务员，其他角色看到的是申办方PM -->
          <a-descriptions-item v-if="isYWAdmin" :label="$t('all.autotext480')"> {{ detailsInfo.businessName }} </a-descriptions-item>
          <a-descriptions-item v-else :label="$t('all.autotext435')">{{ detailsInfo.pmAccount }}</a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext865')">{{ detailsInfo.receiverAccountList }}</a-descriptions-item>
          <a-descriptions-item v-if="isShowAdvancedPay" label="是否垫付">{{  detailsInfo.advancedPay === null ? '-' : detailsInfo.advancedPay === 0 ? '否' : '是' }}</a-descriptions-item>
        </a-descriptions>
        <!-- 项目负责人 -->
        <a-descriptions
          bordered
          :title="$t('all.autotext435')"
          v-if="detailsInfo && detailsInfo.pmName"
          :style="{ margin: '20px 0' }"
          :column="5"
          layout="vertical"
        >
          <a-descriptions-item :label="$t('all.autotext435')"> {{ detailsInfo.pmAccount }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext710')"> {{ detailsInfo.phone }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext1296')"> {{ detailsInfo.email }} </a-descriptions-item>
          <a-descriptions-item :label="$t('all.autotext667')"> {{ detailsInfo.teamStatus | enumValueByKey($const.INVITE_STATUS) }} </a-descriptions-item>
          <a-descriptions-item
            :label="$t('all.autotext187')"
            v-if="$auth('PROJECT.PROJECT_ADMIN_DELETE') && $const.INVITE_STATUS.INVITE.value == detailsInfo.teamStatus"
          >
            <a-popconfirm
              :oktext="$t('all.autotext792')"
              :canceltext="$t('all.autotext975')"
              :title="$t('all.autotext385')"
              @confirm="deletePm"
            >
              <a-button :loading="removeLoading" size="small" type="danger">{{ $t('all.autotext975') }}</a-button>
            </a-popconfirm>
          </a-descriptions-item>
          <a-descriptions-item
            :label="$t('all.autotext187')"
            v-if="$auth('PROJECT.PROJECT_ADMIN_DELETE') && $const.INVITE_STATUS.COMPLETED.value == detailsInfo.teamStatus&& !projectClosed"
          >
            <a-popconfirm
              :oktext="$t('all.autotext379')"
              :canceltext="$t('all.autotext975')"
              :title="$t('all.autotext80')"
              @confirm="deletePm"
            >
              <a-button :loading="removeLoading" size="small" type="danger">{{ $t('all.autotext379') }}</a-button>
            </a-popconfirm>
          </a-descriptions-item>
        </a-descriptions>
        <!-- 详情表单展示 end -->
        <!-- 操作按钮 start -->
        <div
          v-if="$auth('PROJECT.PROJECT_INVITE') && detailsInfo && !detailsInfo.pmName"
          class="table-operator"
          :style="{ margin: '20px 0' }"
        >
          <a-button
            type="primary"
            icon="plus"
            :disabled="projectClosed"
            @click="inviteResponderAdd()"
          >
            {{ $t('all.autotext601') }}
          </a-button>
        </div>
        <template v-if="isAuthorized('PROJECT.PROJECT_MEMBER') || isAuthorized('PROJECT.PROJECT_VISIT') || isAuthorized('PROJECT.PROJECT_REVIEW') || isAuthorized('PROJECT.PROJECT_EXPENSE') || isAuthorized('PROJECT.PROJECT_AGREEMENT')">
          <!-- 操作按钮 end -->
          <a-descriptions :title="$t('all.autotext747')" style="padding-top: 20px" v-if="isAuthorized()"></a-descriptions>
          <!-- tab切换 start -->
          <a-tabs v-model="activedKey" style="margin-bottom: 20px" @change="callback">
            <a-tab-pane :tab="$t('all.autotext1131')" :key="1" v-if="isAuthorized('PROJECT.PROJECT_MEMBER')">
              <!-- 项目成员 -->
              <Members @cancelMember="cancelMember" />
            </a-tab-pane>
            <!-- 受试者 -->
            <!-- <a-tab-pane :tab="$t('all.autotext446')" :key="2" v-if="isAuthorized('PROJECT.PROJECT_PATIENT')">
            <keep-alive>
              <Subject :datailId="parseInt($route.query.id)" />
            </keep-alive>
          </a-tab-pane> -->
            <!-- 访视管理 -->
            <a-tab-pane :tab="$t('all.autotext231')" :key="2" v-if="isAuthorized('PROJECT.PROJECT_VISIT')">
              <keep-alive>
                <Visit />
              </keep-alive>
            </a-tab-pane>
            <!-- 审批流程 -->
            <a-tab-pane :tab="$t('all.autotext1286')" :key="3" v-if="isAuthorized('PROJECT.PROJECT_REVIEW')">
              <keep-alive>
                <Approval :research="researchApprovalInfo" :subject="subjectApprovalInfo" @update="initApproval"/>
              </keep-alive>
            </a-tab-pane>
            <!-- 费用科目 -->
            <a-tab-pane :tab="$t('all.autotext1507')" :key="4" v-if="isAuthorized('PROJECT.PROJECT_EXPENSE')">
              <keep-alive>
                <Expense />
              </keep-alive>
            </a-tab-pane>
            <!-- 项目合同 -->
            <a-tab-pane :tab="$t('all.autotext1257')" v-if="isAuthorized('PROJECT.PROJECT_AGREEMENT')" :key="5">
              <keep-alive>
                <Contract />
              </keep-alive>
            </a-tab-pane>
          <!-- 项目费用 -->
          <!-- <a-tab-pane :tab="$t('all.autotext599')" v-if="isAuthorized('PROJECT.PROJECT_COST')" :key="7">
            <keep-alive>
              <Bill :detailsInfo="detailsInfo" :datailId="parseInt($route.query.id)" />
            </keep-alive>
          </a-tab-pane> -->
          </a-tabs>
        </template>
        <!-- tab切换 end -->
      </a-card>
    </div>

    <!-- 邀请项目负责人modal -->
    <MemberModal
      ref="addMemberRef"
      :projectId="projectId"
      v-model="modalVisible"
      @invitCb="invitCb"
    />
    <!-- 新增/编辑基本信息 -->
    <AddModal
      v-model="editVisible"
      @modalOk="updateEdit"
      :isEdit="1"
      :isEditProject="true"
      :editContent="editContent"
    />
  </div>
</template>

<script>
import moment from 'moment'
import { getProjectDetail, getProjectDelete, getProjectUpdate } from '@/api/overview/contract'
import { getApprovalDetail } from '@/api/overview/approval'
import { deleteLeader } from '@/api/overview/member'
import Members from './components/members'
// import Subject from './components/subject'
import Contract from './components/contract'
// import Bill from './components/bill'
import Visit from './components/visit.vue'
import Approval from './components/approval'
import Expense from './components/expense'
import AddModal from '@/views/overview/allItems/AddModal'
import MemberModal from '@/components/InvitationModal/MemberModal'
import { getUnread } from '@/api/system/message'
import { mapState } from 'vuex'
import storage from 'store'
import { CURRENT_PROJECT } from '@/store/mutation-types'


export default {
  components: {
    Members,
    // Subject,
    Contract,
    // Bill,
    Visit,
    Approval,
    Expense,
    AddModal,
    MemberModal
  },
  provide () {
    return {
      detailsInfoFn: () => this.detailsInfo
    }
  },
  data () {
    const tabPaneArr = [
      {
        key: '1',
        tab: this.$t('all.autotext1131'),
        route: 'index'
      },
      {
        key: '2',
        tab: this.$t('all.autotext446')
      },
      {
        key: '3',
        tab: this.$t('all.autotext911')
      },
      {
        key: '4',
        tab: this.$t('all.autotext1286')
      },
      {
        key: '5',
        tab: this.$t('all.autotext1507')
      },
      {
        key: '6',
        tab: this.$t('all.autotext1257')
      },
      {
        key: '7',
        tab: this.$t('all.autotext599')
      }
    ]
    return {
      columns: [
        {
          title: 'ID',
          key: 'id',
          dataIndex: 'id'
        },
        {
          title: this.$t('all.autotext1150'),
          key: 'ptsNo',
          dataIndex: 'ptsNo'
        },
        {
          title: this.$t('all.autotext550'),
          key: 'applyReason',
          dataIndex: 'applyReason'
        },
        {
          title: this.$t('all.autotext867'),
          key: 'totalAmount',
          dataIndex: 'totalAmount'
        },
        {
          title: this.$t('all.autotext244'),
          key: 'createTime',
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: this.$t('all.autotext1466'),
          key: 'status',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: this.$t('all.autotext187'),
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      detailsInfo: {}, // 详情列表
      activedKey: 1,
      tabPaneArr, // tab切换数据
      rules: {
        phone: [{ required: true, message: this.$t('all.autotext280'), trigger: 'change' }],
        user: [{ required: true, message: this.$t('all.autotext464'), trigger: 'change' }]
      },
      projectId: null,
      modalVisible: false,
      dynamicTitle: '',
      editVisible: false,
      editContent: {},
      researchApprovalInfo: {}, // 研究者审批流
      subjectApprovalInfo: {}, // 受试者审批流
      removeLoading: false,
      pId: null // 项目id 从store中获取的代替从路由中获取
    }
  },
  computed: {
    ...mapState({
      appActiveKey: state => state.app.activeKey
    }),
    isYWAdmin () {
      return this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.YW_ADMIN.value)
    },
    isShowAdvancedPay () {
      return this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.YW_ADMIN.value) || this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.PROJECT_ADMIN.value) || this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value)
    },
    projectClosed () {
      return this.detailsInfo.status === 3
    }
  },
  created () {
    const pro = storage.get(CURRENT_PROJECT)
    if (pro != null && pro.length > 0) {
      const project = JSON.parse(pro)
      this.pId = project.id
      this.$route.query.id = this.pId
    }
    if (this.$route.query.id) {
      this.pId = this.$route.query.id
    }

    getUnread({ proId: this.pId }).then(res => {
      this.$globalVue.$emit('unReadMsgCount', res)
    })
  },
  mounted () {
    this.detailsList()
    this.initTabs()
    this.initApproval()
  },
  methods: {
    isAuthorized (auth) {
      if (!auth) {
        const allProjectMgmtAuthList = [
          'PROJECT.PROJECT_MEMBER',
          'PROJECT.PROJECT_PATIENT',
          'PROJECT.PROJECT_VISIT',
          'PROJECT.PROJECT_REVIEW',
          'PROJECT.PROJECT_EXPENSE',
          'PROJECT.PROJECT_AGREEMENT',
          'PROJECT.PROJECT_COST'
        ]
        return allProjectMgmtAuthList.some(item => this.$auth(item))
      }
      return this.$auth(auth)
    },
    // 获取审批流详情
    async initApproval () {
      if (!this.$auth('PROJECT.PROJECT_FEE_PATIENT_COMMIT')) return
      this.researchApprovalInfo = await getApprovalDetail({
        proId: this.pId || '30695',
        type: 1
      })
      this.subjectApprovalInfo = await getApprovalDetail({
        proId: this.pId || '30695',
        type: 2
      })
    },
    // 根据权限初始化项目管理的tabs
    initTabs () {
      const arr = [
        this.$auth('PROJECT.PROJECT_MEMBER'),
        this.$auth('PROJECT.PROJECT_VISIT'),
        this.$auth('PROJECT.PROJECT_REVIEW'),
        this.$auth('PROJECT.PROJECT_EXPENSE'),
        this.$auth('PROJECT.PROJECT_AGREEMENT'),
        this.$auth('PROJECT.PROJECT_COST')
      ]
      this.activedKey = this.appActiveKey ? this.appActiveKey : arr.findIndex(Boolean) + 1
    },
    detailsList () {
      getProjectDetail({
        id: localStorage.getItem('CURRENT_PROID') || ''
      }).then(res => {
        this.detailsInfo = res
        this.updateProjectInfoInVuex(res)
        const { advancedPay, protocolNo, name, status, stage, budget, no, buildTime, createrId, businessName, serviceCharge, serviceChargePercent, businessCode, sponsorName, customerName } = res

        const sponsorIds = res.sponsorIds?.split(',').map(Number)[0] // 注：后端返回的是个字符串需将其转为数组(split分割后是个string数组，map方法将其转为number数组)
        const receiver = res.receiver ? res.receiver.split(',').map(Number) : []
        this.editContent = { advancedPay, protocolNo, name, sponsorIds, sponsorName, customerName, status, stage, budget, no, buildTime, createrId, businessName, serviceCharge, serviceChargePercent, receiver, businessCode }
        this.editContent.buildTime = moment(this.editContent.buildTime).format('YYYY-MM-DD')
      })
    },
    updateProjectInfoInVuex (res) {
      const haveStored = this.$store.getters.project?.id && this.$store.getters.project?.no
      if (haveStored) return
      this.$store.commit('UPDATE_PROJECT', res)
    },
    callback (key) {
      this.$store.commit('changeActiveKey', key)
    },
    // 邀请项目负责人
    inviteResponderAdd () {
      this.modalVisible = true
      this.projectId = this.$route.query.id
      this.$refs.addMemberRef.getNewRolesList()
    },
    // 点击删除项目
    deleteProject () {
      getProjectDelete({
        id: this.$route.query.id,
        status: this.detailsInfo.status
      }).then(res => {
        this.$message.success(this.$t('all.autotext1455'))
        this.$router.push({ name: 'All' })
      })
    },
    // 判断状态是否可删除
    handleVisibleChange () {
      if (this.detailsInfo.status === 2) {
        this.dynamicTitle = this.$t('all.autotext1481')
      } else {
        this.dynamicTitle = this.$t('all.autotext1234')
      }
    },
    // 点击修改信息
    clickEditMessage () {
      this.editVisible = true
    },
    // 提交修改
    updateEdit (e) {
      const params = { ...e }
      const handleParams = () => {
        delete params.buildTime
        delete params.businessName
        // classify 1-正式 2-测试
        const { classify } = this.detailsInfo
        params.classify = classify
        params.id = this.$route.query.id
      }
      handleParams()
      getProjectUpdate(params)
        .then(res => {
          if (res.message) {
            this.$message.warning(res.message)
          } else {
            this.$message.success(this.$t('all.autotext1108'))
          }
          this.editVisible = false
          this.detailsList()
        })
    },
    cancelMember () {
      this.detailsList()
    },
    deletePm () {
      this.removeLoading = true
      deleteLeader({ id: this.detailsInfo.teamId }).then(res => {
        this.removeLoading = false
        this.detailsList()
        this.$message.success(this.$t('all.autotext470'))
      }).catch(_ => {
        this.removeLoading = false
      })
    },
    invitCb () {
      this.detailsList()
      if (this.activedKey === 1) {
        this.activedKey = 0
        setTimeout(() => {
          this.activedKey = 1
        }, 200)
      }
    }
  }
}
</script>
<style scoped lang="scss"></style>
